package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.impl.impl.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录检查拦截器
 */
@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Reference//远程调用用户缓存信息
    private IUserInfoCacheService userInfoCacheService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {//动态资源

            //从本地获取用户信息Session
            HttpSession session = request.getSession();
            Object userInfo = session.getAttribute(Consts.USER_INFO);
            if (userInfo != null) {
                return true;//session有用户数据放行
            }

            //本地Session没有,从reids查询
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    //cookies的name是userInfoToken
                    if (Consts.USER_INFO_TOKEN.equals(cookie.getName())) {
                        String token = cookie.getValue();
                        //加了前缀的key,作为redis的key
                        String cacheKey = RedisKey.USER_INFO.getCacheKey(token);
                        //json格式的用户信息
                        String json = userInfoCacheService.getUserInfoCache(cacheKey);
                        userInfo = JSON.parseObject(json, UserInfo.class);

                        //存入本地session
                        session.setAttribute(Consts.USER_INFO, userInfo);
                        //放行
                        return true;
                    }
                }
            }

            //强转方法对象
            HandlerMethod hm = (HandlerMethod) handler;

            //判断有无贴注解
            if (!(hm).hasMethodAnnotation(RequiredLogin.class)) {
                return true;//没有注解放行
            }

            //对收藏数的登录状态进行检查
            //未登录:分两种请求情况(ajax请求和普通的请求)
            if (hm.hasMethodAnnotation(ResponseBody.class)) {
                //ajax请求(设置状态码,设置内容类型,把标记的结果写到网页上)
                AjaxResult result = new AjaxResult();
                result.mark("亲,登录后才能收藏。");
                result.setCode(AjaxResult.NO_LOGIN_CODE);
                response.setContentType("text/json;charset=UTF-8");
                response.getWriter().println(JSON.toJSONString(result));
            } else {
                //普通请求
                response.sendRedirect("/login.html");

            }
            //下面代码表示用户没有登录,但是访问的资源需要用户登录
//            response.sendRedirect("/login.html");
            return false;

        }
        return true;//放行静态资源
    }
}
